package com.gccloud.design.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gccloud.design.dao.SdFormDefineDao;
import com.gccloud.design.dto.DesignCenterDTO;
import com.gccloud.design.dto.SdFormDefineDto;
import com.gccloud.design.dto.UserAndRoleBusiOrderConfigDto;
import com.gccloud.design.entity.SdFormDefineEntity;
import com.gccloud.design.feign.BwpOperDockingClient;
import com.gccloud.design.service.SdFormDefineService;
import com.gccloud.design.service.UcBusiOrderShowService;
import com.gccloud.design.vo.SdFormDefineVo;
import com.gccloud.idc.security.shiro.UserUtils;
import com.gccloud.starter.common.exception.GlobalException;
import com.gccloud.starter.common.utils.BeanConvertUtils;
import com.gccloud.starter.common.vo.R;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author wu.yumin
 * @version 1.0.0
 * @Description form
 * @date 2021/6/16 19:38
 */
@Slf4j
@Service
@Data
@ConfigurationProperties(prefix = "form")
public class SdFormDefineServiceImpl extends ServiceImpl<SdFormDefineDao, SdFormDefineEntity> implements SdFormDefineService {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Resource
    private BwpOperDockingClient bwpOperDockingClient;
    @Resource
    private UcBusiOrderShowService ucBusiOrderShowService;

    private Map<String, String> formType;

    @Override
    public R insertFormDefine(SdFormDefineEntity entity) {
        entity.setShardingId(0);
        entity.setCreateOperId(UserUtils.getCurrentUser().getName());
        entity.setCreateOperName(UserUtils.getCurrentUser().getRealName());
        entity.setCreatedTime(sdf.format(new Date()));

        if ("OPERATE".equals(entity.getFormClass()) || "HANDLE".equals(entity.getFormClass())) {
            //创建流程页面模板
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("businessTypeId", entity.getCatalogId());
            paramMap.put("name", entity.getFormName());
            paramMap.put("action", entity.getFormUrl());
            paramMap.put("memo", entity.getFormComments() == null ? "" : entity.getFormComments());
            R result = bwpOperDockingClient.saveFormTemp(JSONObject.toJSONString(paramMap));
            if (result.getCode() != 200) {
                log.info("创建流程页面模板失败");
                throw new GlobalException("创建流程页面模板失败", 500);
            }
            entity.setFlowFormRelaId(Long.parseLong(result.getData().toString()));
        }

        try {
            saveOrUpdate(entity);
            return R.success(entity.getFormId());
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            return R.error();
        }
    }

    @Override
    public SdFormDefineEntity getFormByCd(String formCode) {
        QueryWrapper<SdFormDefineEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(formCode)) {
            throw new IllegalArgumentException("记录不存在");
        }
        queryWrapper.eq("FORM_CODE", formCode);
        SdFormDefineEntity entity = getOne(queryWrapper);
        return entity;
    }

    @Override
    public boolean delFormDefine(Long[] formId) {
        if (formId == null || formId.length < 1) {
            throw new IllegalArgumentException("记录不存在");
        }
        UpdateWrapper<SdFormDefineEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.set("FORM_STATUS", "10DL")
                .set("MODIFIED_OPER_ID", UserUtils.getCurrentUser().getName())
                .set("MODIFIED_OPER_NAME", UserUtils.getCurrentUser().getRealName())
                .set("MODIFIED_TIME", sdf.format(new Date())).in("FORM_ID", formId);
        try {
            return update(updateWrapper);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }


    @Override
    public boolean releaseForm(Long[] formId) {
        if (formId == null || formId.length < 1) {
            throw new IllegalArgumentException("记录不存在");
        }
        UpdateWrapper<SdFormDefineEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.set("FORM_STATUS", "10R")
                .set("RELEASE_TIME", sdf.format(new Date()))
                .set("RELEASE_OPER_ID", UserUtils.getCurrentUser().getName())
                .set("RELEASE_OPER_NAME", UserUtils.getCurrentUser().getRealName()).in("FORM_ID", formId);

        try {
            return update(updateWrapper);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    @Override
    public boolean updateFormDefine(SdFormDefineEntity entity) {
        if (entity.getFormId() == null || entity.getFormId() == 0) {
            throw new IllegalArgumentException("记录不存在");
        }
        UpdateWrapper<SdFormDefineEntity> updateWrapper = new UpdateWrapper();
        try {
            updateWrapper.set("FORM_CODE", entity.getFormCode())
                    .set("FORM_NAME", entity.getFormName())
                    .set("FORM_VERSION", entity.getFormVersion())
                    .set("FORM_URL", entity.getFormUrl())
                    .set("FORM_TYPE", entity.getFormType())
                    .set("FORM_CLASS", entity.getFormClass())
                    .set("CATALOG_ID", entity.getCatalogId())
                    .set("CATALOG_CODE", entity.getCatalogCode())
                    .set("CATALOG_NAME", entity.getCatalogName())
                    .set("FORM_COMMENTS", entity.getFormComments())
                    .set("MODIFIED_OPER_NAME", UserUtils.getCurrentUser().getName())
                    .set("MODIFIED_TIME", sdf.format(new Date()))
                    .set("MODIFIED_OPER_ID", UserUtils.getCurrentUser().getRealName())
                    .eq("FORM_ID", entity.getFormId());
            return update(updateWrapper);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    @Override
    public Map<String, Object> queryFormList(SdFormDefineDto searchDTO) {
        Page<SdFormDefineVo> page = new Page<>(searchDTO.getCurrent(), searchDTO.getSize());
        List<SdFormDefineVo> list = this.baseMapper.getFormListByPage(searchDTO, page);
        Map<String, Object> map = new HashMap<>(3);
        map.put("list", list);
        map.put("totalCount", page.getTotal());
        return map;

    }

    @Override
    public List<SdFormDefineEntity> queryList(Long busiType, String formClass, String formType) {
        QueryWrapper<SdFormDefineEntity> queryWrapper = new QueryWrapper<>();
        if (busiType != 0 && busiType != null) {
            queryWrapper.eq("CATALOG_CODE", busiType);
        }
        if (!StringUtils.isEmpty(formClass)) {
            queryWrapper.eq("FORM_CLASS", formClass);
        }
        if (!StringUtils.isEmpty(formType)) {
            queryWrapper.eq("FORM_TYPE", formType);
        }
        queryWrapper.eq("FORM_STATUS", "10R");
        queryWrapper.orderByDesc("CREATED_TIME");
        return list(queryWrapper);
    }

    /**
     * 新增多个表单
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveList(Map<String,Object> param) {
        String s = JSONObject.toJSONString(param.get("designDto"));
            DesignCenterDTO dto=JSONObject. parseObject(s,DesignCenterDTO.class);
        String str = JSONObject.toJSONString(param.get("configDto"));
        UserAndRoleBusiOrderConfigDto userDto=JSONObject.parseObject(str,UserAndRoleBusiOrderConfigDto.class);
        Set<String> keySet = formType.keySet();
        for(String key : keySet){
            key=key.toUpperCase();
            dto.setFormType(key);
            if(key.equals("MONITORY")){
                dto.setFormUrl(dto.getFormUrl()+"&activityRepoId=MonitoringStatus");
            }else if(key.equals("DETAIL")){
                dto.setFormUrl(dto.getFormUrl()+"&activityRepoId=QueryStatus");
            }
            SdFormDefineEntity entity = BeanConvertUtils.convert(dto, SdFormDefineEntity.class);
            R res=insertFormDefine(entity);
            if (res.getCode()!=200){
                R.error(res.getMsg());
            }
            if(key.equals("INPUT")){
                List<SdFormDefineEntity> list=new ArrayList<>();
                list.add(entity);
                userDto.setSdFormDefineEntityList(list);
                Boolean r=ucBusiOrderShowService.userAndRoleBusiOrderConfig(userDto);
                if (!r){
                    R.error();
                }
            }
        }
        return R.success();
    }

    /**
     * 低代码平台下线表单
     * @param catalogCode
     * @return
     */
    @Override
    public Boolean downForm(String catalogCode) {
        if (StringUtils.isEmpty(catalogCode)) {
            throw new IllegalArgumentException("请传入正确的值");
        }
        boolean result=true;
        // 根据formUrl查询自定义表单
        QueryWrapper<SdFormDefineEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CATALOG_CODE", catalogCode).eq("FORM_CLASS", "USER_DEFINE_FORM").eq("FORM_TYPE", "INPUT").eq("FORM_STATUS", "10R");
        List<SdFormDefineEntity> list = list(queryWrapper);
        if(list!=null&&list.size()>0){
            int i=0;
            Long[] ids=new Long[list.size()];
            for(SdFormDefineEntity sdFormDefineEntity:list){
                ids[i++]=sdFormDefineEntity.getFormId();
            }
            boolean res1= delFormDefine(ids);
            int res2=ucBusiOrderShowService.delByFormId(ids);
            result=res1&&res2>0;
        }
        return result;
    }
}
